<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// GET 请求处理
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    
    switch ($action) {
        case 'list':
            // 获取帖子列表
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $pageSize = isset($_GET['pageSize']) ? (int)$_GET['pageSize'] : 10;
            $offset = ($page - 1) * $pageSize;
            $keyword = isset($_GET['keyword']) ? $_GET['keyword'] : '';

            if ($keyword) {
                // 搜索帖子
                $keyword = "%{$keyword}%";
                $sql = "SELECT p.*, u.name, u.avatar 
                        FROM posts p 
                        LEFT JOIN users u ON p.user_id = u.id 
                        WHERE p.status = 1 
                        AND (p.title LIKE ? OR p.content LIKE ?) 
                        ORDER BY p.created_at DESC";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ss", $keyword, $keyword);
            } else {
                // 获取帖子列表
                $sql = "SELECT p.*, u.name, u.avatar 
                        FROM posts p 
                        LEFT JOIN users u ON p.user_id = u.id 
                        WHERE p.status = 1 
                        ORDER BY p.created_at DESC 
                        LIMIT ?, ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ii", $offset, $pageSize);
            }

            $stmt->execute();
            $result = $stmt->get_result();
            $posts = [];
            while ($row = $result->fetch_assoc()) {
                $row['created_at'] = date('Y-m-d H:i', strtotime($row['created_at']));
                $posts[] = $row;
            }
            echo json_encode(['status' => 'success', 'posts' => $posts]);
            break;

        case 'detail':
            // 获取帖子详情
            $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
            if (!$id) {
                echo json_encode(['status' => 'error', 'message' => '帖子ID不能为空']);
                exit;
            }

            // 更新浏览次数
            $conn->query("UPDATE posts SET view_count = view_count + 1 WHERE id = {$id}");

            $sql = "SELECT p.*, u.name, u.avatar 
                    FROM posts p 
                    LEFT JOIN users u ON p.user_id = u.id 
                    WHERE p.id = ? AND p.status = 1";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $post = $result->fetch_assoc();
            
            if ($post) {
                $post['created_at'] = date('Y-m-d H:i', strtotime($post['created_at']));
                echo json_encode(['status' => 'success', 'post' => $post]);
            } else {
                echo json_encode(['status' => 'error', 'message' => '帖子不存在']);
            }
            break;

        case 'comments':
            // 获取评论列表
            $postId = isset($_GET['post_id']) ? (int)$_GET['post_id'] : 0;
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
            $offset = ($page - 1) * $limit;

            if (!$postId) {
                echo json_encode(['status' => 'error', 'message' => '帖子ID不能为空']);
                exit;
            }

            $sql = "SELECT c.*, u.name, u.avatar 
                    FROM comments c 
                    LEFT JOIN users u ON c.user_id = u.id 
                    WHERE c.post_id = ? AND c.status = 1 
                    ORDER BY c.created_at DESC 
                    LIMIT ?, ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iii", $postId, $offset, $limit);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $comments = [];
            while ($row = $result->fetch_assoc()) {
                $row['created_at'] = date('Y-m-d H:i', strtotime($row['created_at']));
                $comments[] = $row;
            }
            echo json_encode(['status' => 'success', 'comments' => $comments]);
            break;

        case 'myPosts':
            // 获取我的帖子列表
            $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $pageSize = isset($_GET['pageSize']) ? (int)$_GET['pageSize'] : 10;
            $offset = ($page - 1) * $pageSize;

            if (!$userId) {
                echo json_encode(['status' => 'error', 'message' => '用户ID不能为空']);
                exit;
            }

            $sql = "SELECT p.*, u.name, u.avatar 
                    FROM posts p 
                    LEFT JOIN users u ON p.user_id = u.id 
                    WHERE p.status = 1 AND p.user_id = ? 
                    ORDER BY p.created_at DESC 
                    LIMIT ?, ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iii", $userId, $offset, $pageSize);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $posts = [];
            while ($row = $result->fetch_assoc()) {
                $row['created_at'] = date('Y-m-d H:i', strtotime($row['created_at']));
                $posts[] = $row;
            }
            echo json_encode(['status' => 'success', 'posts' => $posts]);
            break;

        default:
            echo json_encode(['status' => 'error', 'message' => '未知的GET操作']);
            break;
    }
}
// POST 请求处理
else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';

    switch ($action) {
        case 'addComment':
            // 添加评论
            $postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;
            $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
            $content = isset($_POST['content']) ? trim($_POST['content']) : '';

            if (!$postId || !$userId || !$content) {
                echo json_encode(['status' => 'error', 'message' => '参数错误']);
                exit;
            }

            $sql = "INSERT INTO comments (post_id, user_id, content) VALUES (?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iis", $postId, $userId, $content);
            
            if ($stmt->execute()) {
                // 更新帖子评论数
                $conn->query("UPDATE posts SET comment_count = comment_count + 1 WHERE id = {$postId}");
                echo json_encode(['status' => 'success']);
            } else {
                echo json_encode(['status' => 'error', 'message' => '评论失败']);
            }
            break;

        case 'toggleLike':
            // 点赞/取消点赞
            $postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;
            $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;

            if (!$postId || !$userId) {
                echo json_encode(['status' => 'error', 'message' => '参数错误']);
                exit;
            }

            // 更新点赞数
            $conn->query("UPDATE posts SET like_count = like_count + 1 WHERE id = {$postId}");
            echo json_encode(['status' => 'success']);
            break;

        case 'uploadImage':
            // 检查是否有文件上传
            if (!isset($_FILES['image'])) {
                echo json_encode([
                    'status' => 'error',
                    'message' => '未上传图片'
                ]);
                exit;
            }

            $image = $_FILES['image'];

            // 检查上传是否成功
            if ($image['error'] !== UPLOAD_ERR_OK) {
                echo json_encode([
                    'status' => 'error',
                    'message' => '图片上传失败'
                ]);
                exit;
            }

            // 检查文件类型
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
            if (!in_array($image['type'], $allowedTypes)) {
                echo json_encode([
                    'status' => 'error',
                    'message' => '不支持的图片格式'
                ]);
                exit;
            }

            // 设置上传目录
            $uploadDir = 'uploads/posts/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            // 获取文件扩展名
            $fileExtension = pathinfo($image['name'], PATHINFO_EXTENSION);
            
            // 生成新的文件名（基于当前时间戳和随机字符串）
            $newFileName = date('YmdHis') . '_' . uniqid() . '.' . $fileExtension;

            // 完整文件路径
            $imagePath = $uploadDir . $newFileName;

            // 移动上传的文件
            if (move_uploaded_file($image['tmp_name'], $imagePath)) {
                echo json_encode([
                    'status' => 'success',
                    'path' => 'uploads/posts/' . $newFileName
                ]);
            } else {
                echo json_encode([
                    'status' => 'error',
                    'message' => '图片保存失败'
                ]);
            }
            break;

        case 'create':
            // 创建帖子
            $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
            $title = isset($_POST['title']) ? trim($_POST['title']) : '';
            $content = isset($_POST['content']) ? trim($_POST['content']) : '';
            $image = $_FILES['image'] ?? null;
            
            if (!$userId || !$title || !$content) {
                echo json_encode(['status' => 'error', 'message' => '参数错误']);
                exit;
            }
            
            // 处理图片上传
            $imagePath = '';
            if ($image && $image['error'] === UPLOAD_ERR_OK) {
                $uploadDir = 'uploads/posts/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                // 获取文件扩展名
                $fileExtension = pathinfo($image['name'], PATHINFO_EXTENSION);
                
                // 生成新的文件名
                $newFileName = date('YmdHis') . '_' . uniqid() . '.' . $fileExtension;
                
                // 完整文件路径
                $imagePath = $uploadDir . $newFileName;
                $fullPath = $uploadDir . $newFileName;
                
                if (!move_uploaded_file($image['tmp_name'], $fullPath)) {
                    echo json_encode(['status' => 'error', 'message' => '图片上传失败']);
                    exit;
                }
            }
            
            $sql = "INSERT INTO posts (user_id, title, content, image) VALUES (?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("isss", $userId, $title, $content, $imagePath);
            
            if ($stmt->execute()) {
                echo json_encode(['status' => 'success']);
            } else {
                echo json_encode(['status' => 'error', 'message' => '发布失败']);
            }
            break;
        
        case 'deletePost':
            // 删除帖子
            $postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;
            $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;

            if (!$postId || !$userId) {
                echo json_encode(['status' => 'error', 'message' => '参数错误']);
                exit;
            }

            // 验证是否是帖子作者
            $sql = "SELECT user_id FROM posts WHERE id = ? AND status = 1";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $postId);
            $stmt->execute();
            $result = $stmt->get_result();
            $post = $result->fetch_assoc();

            if (!$post || $post['user_id'] != $userId) {
                echo json_encode(['status' => 'error', 'message' => '无权删除此帖子']);
                exit;
            }

            // 软删除帖子
            $sql = "UPDATE posts SET status = 0 WHERE id = ? AND user_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ii", $postId, $userId);

            if ($stmt->execute()) {
                echo json_encode(['status' => 'success']);
            } else {
                echo json_encode(['status' => 'error', 'message' => '删除失败']);
            }
            break;    

        default:
            echo json_encode(['status' => 'error', 'message' => '未知的POST操作']);
            break;

        
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '不支持的请求方法']);
}

$conn->close();
?> 